//
//  SendFileViewController.m
//  Connectivity
//
//  Created by James on 17/1/9.
//  Copyright © 2023年 James. All rights reserved.
//

#import "SendFileViewController.h"
#import "AnimationView.h"
#import "Masonry.h"
#import <MultipeerConnectivity/MultipeerConnectivity.h>
#import "ProgressIconBtn.h"
#import "AssetHelper.h"
#import "SWProgressView.h"
#import "JKFilePathOperationExtension.h"

@interface SendFileViewController ()<MCSessionDelegate, MCNearbyServiceAdvertiserDelegate, MCNearbyServiceBrowserDelegate>

@property (weak, nonatomic) UILabel *tipLable;
@property (weak, nonatomic) ProgressIconBtn *receiverBtn;

@property (strong, nonatomic) NSTimer *timer;
@property (weak, nonatomic) AnimationView *animationView;
@property (strong,nonatomic) MCSession *session;
@property (strong,nonatomic) MCNearbyServiceAdvertiser *nearbyServiceAdveriser;
@property (strong, nonatomic) MCNearbyServiceBrowser *nearbyServiceBrowser;
@property (strong, nonatomic) MCPeerID *peerID;
@property (nonatomic, strong) SWProgressView *progressView;
@property (nonatomic, strong) NSMutableArray *tmpFiles;

@end

@implementation SendFileViewController{
    NSInteger _totalCount;
    NSInteger _finishCount;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"发送数据";
    [self setLeftItemWithIcon:[UIImage imageNamed:@"back"] title:nil selector:@selector(onClickBack)];
    [self addOwnViews];
    [self scanNearbyPeer];
    _finishCount = 0;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    if (!self.receiverBtn.hidden) {
        self.receiverBtn.hidden = YES;
    }
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    if (self.nearbyServiceAdveriser) {
        [self.nearbyServiceAdveriser stopAdvertisingPeer];
    }
    if (self.nearbyServiceBrowser) {
        [self.nearbyServiceBrowser stopBrowsingForPeers];
    }
}

#pragma mark - Private

- (void)onClickBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addOwnViews
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    //tipLable
    UILabel *lable = [[UILabel alloc] init];
    lable.text = @"正在搜索附近的设备...";
    lable.textColor = MainThemeColor;
    [self.view addSubview:lable];
    __weak typeof(self) ws = self;
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(ws.view.mas_centerX);
        make.top.offset(100);
    }];
    
    //progressIconBtn
    ProgressIconBtn *btn = [[ProgressIconBtn alloc] init];
    CGFloat btnWH = 100;
    btn.frame = CGRectMake(0, 0, btnWH, btnWH);
    btn.center = self.view.center;
    btn.backgroundColor = [UIColor clearColor];
    btn.hidden = YES;
    [btn addTarget:self action:@selector(receiverBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    self.receiverBtn = btn;
}

//扫描附近设备
- (void)scanNearbyPeer
{
    //开启扫描动画
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(clickAnimation) userInfo:nil repeats:YES];
    
    //创建会话(两边的回话类型必须一致)
    MCPeerID *peerID = [[MCPeerID alloc] initWithDisplayName:[[UIDevice currentDevice] name]];
    self.session = [[MCSession alloc] initWithPeer:peerID securityIdentity:nil encryptionPreference:MCEncryptionRequired];
    self.session.delegate = self;
    
    //广播通知(广播是通过serviceType来区分，所以监听广播的serviceType必须相同，不然监听不到)
    self.nearbyServiceAdveriser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:peerID discoveryInfo:nil serviceType:@"rsp-sender"];
    self.nearbyServiceAdveriser.delegate = self;
    [self.nearbyServiceAdveriser startAdvertisingPeer];
    
    //监听广播
    self.nearbyServiceBrowser = [[MCNearbyServiceBrowser alloc] initWithPeer:peerID serviceType:@"rsp-receiver"];
    self.nearbyServiceBrowser.delegate = self;
    [self.nearbyServiceBrowser startBrowsingForPeers];
}

//扫描动画
-(void)clickAnimation
{
    CGFloat w = [UIScreen mainScreen].bounds.size.width - 60;
    AnimationView *animationView = [[AnimationView alloc] initWithFrame:CGRectMake(30, 150, w, w)];
    animationView.userInteractionEnabled = NO;
    animationView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:animationView];
    self.animationView = animationView;
    [UIView animateWithDuration:2 animations:^{
        animationView.transform=CGAffineTransformScale(animationView.transform, 4, 4);
        animationView.alpha=0;
    } completion:^(BOOL finished) {
        [animationView removeFromSuperview];
    }];
    
}

- (void)stopAnimation{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    [self.animationView removeFromSuperview];
}

//显示扫描到的节点
- (void)showPeer
{
    self.receiverBtn.hidden = NO;
    self.receiverBtn.nickName.text = self.peerID.displayName;
    
    CATransition *transition = [CATransition animation];
    transition.duration = 1.5f;
    transition.type = @"rippleEffect";
    [self.receiverBtn.layer addAnimation:transition forKey:nil];
    [self.view bringSubviewToFront:self.receiverBtn];
}

//隐藏扫描到的节点
- (void)hidePeer
{
    CATransition *transition = [CATransition animation];
    transition.duration = 1.5f;
    transition.type = @"rippleEffect";
    [self.receiverBtn.layer addAnimation:transition forKey:nil];
    [self.view bringSubviewToFront:self.receiverBtn];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.receiverBtn.hidden = YES;
    });
}

- (void)receiverBtnClicked:(UIButton *)btn
{
    //发出邀请
    //context 携带请求的附加信息
    [self.nearbyServiceBrowser invitePeer:self.peerID toSession:self.session withContext:nil timeout:30];
}

- (void)sendFileByPath:(NSString *)path{
    //这里利用数据源的方式来发送数据
    //这里必须要用fileURLWithPath 用String会报错Unsupported resource type
    __weak typeof(self) ws = self;
    NSProgress *progress = [self.session sendResourceAtURL:[NSURL fileURLWithPath:path] withName:[path lastPathComponent] toPeer:[self.session.connectedPeers firstObject] withCompletionHandler:^(NSError * _Nullable error) {
        if (error) {
            NSLog(@"发送源数据发生错误：%@", [error localizedDescription]);
        }else {
//            __weak typeof(self) ws = self;
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [ws.receiverBtn setProgressValue:0];
//            });
            [ws.tmpFiles addObject:path];
        }
    }];
    [progress addObserver:self forKeyPath:@"completedUnitCount" options:NSKeyValueObservingOptionNew context:nil];
}

#pragma mark - MCNearbyServiceBrowserDelegate

// 发现了附近的广播节点
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID
withDiscoveryInfo:(nullable NSDictionary<NSString *, NSString *> *)info
{
    NSLog(@"发现了节点：%@", peerID.displayName);
    //这里只考虑一个节点的情况:发现节点就停止搜索
    [browser stopBrowsingForPeers];
    
    self.peerID = peerID;
    
    //更新UI显示
    [self showPeer];
}

// 广播节点丢失
- (void)browser:(MCNearbyServiceBrowser *)browser lostPeer:(MCPeerID *)peerID
{
    NSLog(@"丢失了节点：%@", peerID.displayName);
    //这里只考虑一个节点的情况
    [browser startBrowsingForPeers];
    
    self.peerID = nil;
    
    //更新UI显示
    [self hidePeer];
}

// 搜索失败回调
- (void)browser:(MCNearbyServiceBrowser *)browser didNotStartBrowsingForPeers:(NSError *)error
{
    [browser stopBrowsingForPeers];
    NSLog(@"搜索出错：%@", error.localizedDescription);
}

#pragma mark - MCNearbyServiceAdvertiserDelegate

// 收到节点邀请回调
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser
didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(nullable NSData *)context invitationHandler:(void (^)(BOOL accept, MCSession * __nullable session))invitationHandler
{
    //只有发送者发出邀请，接收者接收邀请
}

// 广播失败回调
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didNotStartAdvertisingPeer:(NSError *)error
{
    [advertiser stopAdvertisingPeer];
    NSLog(@"%@节点广播失败", advertiser.myPeerID.displayName);
}

#pragma mark - MCSessionDelegate

// 会话状态改变回调
- (void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state
{
    switch (state) {
        case MCSessionStateNotConnected://未连接
            NSLog(@"未连接");
            break;
        case MCSessionStateConnecting://连接中
            NSLog(@"连接中");
            break;
        case MCSessionStateConnected://连接完成
        {
            NSLog(@"连接完成");
            
            // 创建一个串行队列
            dispatch_queue_t serialQueue = dispatch_queue_create("com.example.serialQueue", DISPATCH_QUEUE_SERIAL);
            
            //发送联系人
            if (self.sendContact) {
                _totalCount++;
                dispatch_block_t task = ^{
                    [self sendFileByPath:ASSETHELPER.contactFilePath];
                };
                dispatch_sync(serialQueue, task);
            }
            
            //发送照片
            if (self.sendPhoto) {
                
                for (PHAsset *asset in ASSETHELPER.allPhotos) {
                    _totalCount++;
                    dispatch_block_t task = ^{
                        [ASSETHELPER requestImageDataForAsset:asset andResultBlock:^(NSString *fliePath) {
                            [self sendFileByPath:fliePath];
                        }];
                    };
                    dispatch_sync(serialQueue, task);
                }
            }
            //发送视频
            if (self.sendVideo) {
                for (PHAsset *asset in ASSETHELPER.allVideos) {
                    _totalCount++;
                    dispatch_block_t task = ^{
                        [ASSETHELPER requestVideoDataForAsset:asset andResultBlock:^(NSString *fliePath) {
                            [self sendFileByPath:fliePath];
                        }];
                    };
                    dispatch_sync(serialQueue, task);
                }
            }
            
            
            // 等待队列中的任务执行完毕
            dispatch_sync(serialQueue, ^{
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self.progressView setProgressText:[NSString stringWithFormat:@"已传输%@条/共%@条",@(_finishCount),@(_totalCount)]];
//                    [self.progressView showWithDefaultProgress];
                    
                    [self stopAnimation];
//                    [SVProgressHUD showImage:[UIImage imageNamed:@"send"] status:[NSString stringWithFormat:@"已传输%@条/共%@条",@(_finishCount),@(_totalCount)]];
                    [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"已传输%@条/共%@条",@(_finishCount),@(_totalCount)]];

                });
                
                
            });
            
        }
            break;
    }
}

// 普通数据传输
- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID
{
    NSLog(@"普通数据%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}

// 数据流传输
- (void)session:(MCSession *)session didReceiveStream:(NSInputStream *)stream withName:(NSString *)streamName fromPeer:(MCPeerID *)peerID
{
    NSLog(@"数据流%@", peerID.displayName);
}

// 数据源传输开始
- (void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress
{
    NSLog(@"数据传输开始");
}

// 数据传输完成回调
- (void)session:(MCSession *)session didFinishReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID atURL:(NSURL *)localURL withError:(nullable NSError *)error
{
    NSLog(@"数据传输结束%@----%@", localURL.absoluteString, error);
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSProgress *progress = (NSProgress *)object;

    if (progress.fractionCompleted == 1.0) {
        _finishCount++;
        NSLog(@"已完成%@个传输", @(_finishCount));
        dispatch_async(dispatch_get_main_queue(), ^{
            if (_finishCount == _totalCount) {
                [SVProgressHUD showSuccessWithStatus:@"传输完成"];
                //            [self.progressView dismiss];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                //                [self.progressView setProgress:_finishCount/_totalCount];
                //                [self.progressView setProgressText:[NSString stringWithFormat:@"已传输%@条/共%@条",@(_finishCount),@(_totalCount)]];
                
                [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"已传输%@条/共%@条",@(_finishCount),@(_totalCount)]];
                
                
                
                //            [SVProgressHUD showProgress:_finishCount/_totalCount status:[NSString stringWithFormat:@"已传输%@条/共%@条",@(_finishCount),@(_totalCount)]];
                
            }
        });
        
        if (_finishCount - 1 < self.tmpFiles.count) {
            if ([JKFilePathOperationExtension jkJudgeFileOrFolderExists:self.tmpFiles[_finishCount - 1]]) {
                [JKFilePathOperationExtension jKRemovefile:self.tmpFiles[_finishCount - 1]];
            }
        }
        [progress removeObserver:self forKeyPath:@"completedUnitCount" context:nil];
    }
}


- (SWProgressView *)progressView{
    if(!_progressView){
        __weak typeof(self) ws = self;
        _progressView = [[SWProgressView alloc] initWithTitle:@"正在传输" andCancelBlock:^{
            [ws.session disconnect];
        }];
    }
    return _progressView;
}

- (NSMutableArray *)tmpFiles{
    if(!_tmpFiles){
        _tmpFiles = [[NSMutableArray alloc] init];
    }
    return _tmpFiles;
}
@end
